<template>
	<view class="container">
		<view class="header">
			<view class="order-type">
				<text
					class="type-item"
					v-for="(type, index) in orderTypes"
					:key="index"
					@tap="changeType(type.type)"
					:class="[type.type == orderType ? 'active' : '', index == 0 ? 'type-first' : '', index == orderTypes.length - 1 ? 'type-last' : '']"
				>
					{{ type.text }}
				</text>
			</view>
			<!-- 到店自取 -->
			<view v-if="orderType == 1" class="order-shop">
				<text class="iconfont icon-dizhi pos-icon"></text>
				<view class="shop-info">
					<text class="shop-name">{{ shop.name }}</text>
					<text class="shop-address">{{ shop.address }}</text>
				</view>
			</view>
			<!-- 配送到家 -->
			<view v-else class="order-address" @tap="gotoAddress">
				<text class="iconfont icon-dizhi pos-icon"></text>
				<view class="address-info" v-if="address != null">
					<text class="address">{{ address.address }}</text>
					<view class="info">
						<text class="name">{{ address.name }} {{ address.phone }}</text>
					</view>
				</view>
				<view v-else style="display: flex; align-items: center; flex: 1; margin-left: 20rpx; font-weight: bold">请填写收货地址</view>
				<view style="display: flex; align-items: center; padding: 0 20rpx">
					<text class="iconfont icon-qianwang" style="font-size: 40rpx"></text>
				</view>
			</view>
		</view>
		<view class="order-content">
			<view class="order-info">
				<view class="border-bottom-grey" style="padding: 20rpx 0; font-size: 30rpx">商品信息</view>
				<view class="border-bottom-grey">
					<view class="goods-item" v-for="(goods, index) in goodsList" :key="index">
						<muqian-lazyLoad :src="goods.thumbnail" width="120rpx" height="120rpx"></muqian-lazyLoad>
						<!--<image class="goods-image" :src="baseUrl + goods.thumbnail" /> -->
						<view class="goods-info">
							<text class="goods-name">{{ goods.name }}</text>
							<text class="goods-spec">{{ goods.spec }}</text>
							<text v-if="goods.styleInfo.styleName" class="goods-spec">{{ goods.styleInfo.styleName }}</text>
						</view>
						<view class="purchase">
							<view class="goods-price">¥ {{ goods.price.toFixed(2) }}</view>
							<view class="purchase-num">x {{ goods.num }}</view>
						</view>
					</view>
				</view>

				<view class="border-bottom-grey select-time-box" @tap="showTimePopup">
					<block v-if="orderType == 1">
						<text>门店自提时间</text>
						<view style="flex: 1; text-align: right">
							<text class="pick-time">{{ pickTime }}</text>
							<text class="iconfont icon-qianwang" style="margin-left: 5rpx"></text>
						</view>
					</block>
					<block v-else>
						<text>同城配送时间</text>
						<view style="flex: 1; text-align: right">
							<text class="delivery-time">{{ deliveryTime }}</text>
							<text class="iconfont icon-qianwang" style="margin-left: 5rpx"></text>
						</view>
					</block>
				</view>

				<view class="border-bottom-grey user-message" @tap="gotoUserMessage">
					<text>买家留言</text>
					<view style="flex: 1; text-align: right">
						<text>{{ userMessage }}</text>
						<text class="iconfont icon-qianwang" style="margin-left: 5rpx"></text>
					</view>
				</view>
			</view>

			<!-- 订单优惠 -->
			<view class="order-activity" style="margin-top: 30rpx">
				<view class="border-bottom-grey discount">
					<text>折扣</text>
					<view style="flex: 1; text-align: right">
						<text v-if="discount == 1">暂无</text>
						<text v-else style="color: #ff5a14">{{ discount * 100 }}折</text>
					</view>
				</view>
				<view class="coupon" @tap="$refs.couponPopup.open('bottom')">
					<text>优惠券</text>

					<view style="flex: 1; text-align: right">
						<text v-if="couponList.length > 0 && currentCouponIdx == -1">可用{{ couponNum }}张</text>
						<text v-if="couponList.length > 0 && currentCouponIdx != -1" style="color: #ff5a14">优惠{{ couponList[currentCouponIdx].couponPrice }}元</text>
						<text v-if="couponList.length == 0" style="color: #999999">暂无可用</text>
						<text class="iconfont icon-qianwang" style="margin-left: 5rpx"></text>
					</view>
				</view>
			</view>
			<!-- 			<view class="coupon-wrapper" style="margin-top: 30rpx" @tap="$refs.couponPopup.open('bottom')">
				
			</view>

			<view class="discount-wrapper" style="margin-top: 30rpx">
				
			</view> -->
		</view>

		<!-- 正下方固定工具栏 -->
		<view style="height: 120rpx">
			<view class="purchase-tool">
				<view class="tool-one">
					<text>已优惠：¥ {{ activityPrice.toFixed(2) }}</text>
				</view>
				<view class="tool-two">
					<text>合计：</text>
					<text class="pay-price">¥ {{ payPrice.toFixed(2) }}</text>
				</view>
				<view class="tool-three">
					<text class="purchase" @tap="gotoCashDesk">去付款</text>
				</view>
			</view>
		</view>

		<!-- 时间选择 -->
		<uni-popup ref="timePopup" class="popup" background-color="#fff" :mask-click="false">
			<picker-view class="picker-view" :value="pickerArray" @change="bindChange">
				<picker-view-column>
					<view class="item" v-for="(item, index) in years" :key="index" :class="index == pickerArray[0] ? 'indicator-item' : ''">{{ item }}年</view>
				</picker-view-column>
				<picker-view-column>
					<view class="item" v-for="(item, index) in months" :key="index" :class="index == pickerArray[1] ? 'indicator-item' : ''">{{ item }}月</view>
				</picker-view-column>
				<picker-view-column>
					<view class="item" v-for="(item, index) in days" :key="index" :class="index == pickerArray[2] ? 'indicator-item' : ''">{{ item }}日</view>
				</picker-view-column>
				<picker-view-column>
					<view class="item" v-for="(item, index) in times" :key="index" :class="index == pickerArray[3] ? 'indicator-item' : ''">{{ item }}</view>
				</picker-view-column>
			</picker-view>

			<view class="tools">
				<text class="cancel" @tap="cancel">取消</text>
				<text>请选择门店自提时间</text>
				<text class="sure" @tap="sure">确定</text>
			</view>
		</uni-popup>

		<!-- 优惠券选择 -->
		<uni-popup ref="couponPopup" class="popup" background-color="#fff">
			<view class="coupon-list">
				<view class="coupon-item" v-for="(coupon, couponIdx) in couponList" :key="couponIdx">
					<view class="item-left" :class="currentCouponStatus == 1 || currentCouponStatus == 2 ? 'lose-item-style ' : 'no-use-item-style'">
						<view class="item-serration"></view>
						<view>
							<text>¥</text>
							<text style="font-size: 80rpx">{{ coupon.couponPrice }}</text>
						</view>
						<view style="font-size: 28rpx">满{{ coupon.requirePrice }}元可用</view>
					</view>
					<view class="item-right">
						<view style="height: 100rpx; padding-top: 15rpx; color: #6b3c19; font-size: 28rpx; display: flex">
							<text>{{ coupon.name }}</text>
							<view style="padding-left: 10rpx">
								<text>×</text>
								<text>{{ coupon.couponNum }}</text>
								<text>张</text>
							</view>
						</view>
						<view style="height: 60rpx; padding-bottom: 20rpx; display: flex; justify-content: space-between">
							<text style="color: #999999; font-size: 25rpx">{{ coupon.useScene }}</text>
							<text style="padding: 5rpx 20rpx; font-size: 25rpx; color: #fff; background-color: #ff5a14; border-radius: 50rpx" @tap="selectCoupon(couponIdx)">
								选择
							</text>
						</view>
						<view style="height: 40rpx; display: flex; align-items: center; color: #999999; font-size: 20rpx; border-top: 1rpx solid #eff1f4">
							{{ coupon.startTime }} ~ {{ coupon.endTime }}
						</view>
					</view>
				</view>
			</view>
		</uni-popup>
	</view>
</template>

<script>
import { getSysTime } from '@/api/common';
import { getDefaultAddress, getUserDiscount, listUserCoupon } from '@/api/user';
import { addOrder } from '@/api/order';
import dateUtil from '@/utils/dateUtil.js';
export default {
	onLoad(params) {
		this.goodsList = JSON.parse(decodeURIComponent(params.goodsList));
		// this.getTotalPrice();
		console.log(this.goodsList);
	},
	onShow() {
		// 监听用户留言信息
		uni.$once('getUserMessage', (userMessage) => {
			this.userMessage = userMessage;
		});
		// 获取用户默认地址
		this.getDefaultAddress();
		// 获取系统当前时间
		this.getSystemTime();
		// 获取用户折扣
		this.getUserDiscount();
		// 获取用户可用优惠券
		this.getUserCouponList();
	},
	data() {
		return {
			goodsList: [],
			// totalPrice: 0,
			// activityPrice: 0,
			discount: 1,
			userMessage: '',
			orderType: 1,
			orderTypes: [
				{
					text: '到店自取',
					type: 1
				},
				{
					text: '配送到家',
					type: 2
				}
			],
			years: [],
			months: [],
			days: [],
			times: [],
			pickTime: '',
			deliveryTime: '',
			timeTemp: '',
			pickerArray: [0, 0, 0, 0],
			shop: uni.getStorageSync('shop'),
			address: null,
			date: new Date(), // 此处创建对象只是为了定义为Date类型，后面会获取服务器时间，重新赋值
			couponList: [],
			currentCouponIdx: -1
		};
	},
	computed: {
		totalPrice() {
			let totalPrice = 0;
			this.goodsList.forEach((item) => {
				totalPrice += item.price * item.num;
			});
			// console.log(this.discount, totalPrice, totalPrice * this.discount);
			return totalPrice;
		},
		activityPrice() {
			// 先打折再减优惠
			// let activityPrice = 0;
			// if (this.currentCouponIdx != -1) {
			// 	activityPrice += this.couponList[this.currentCouponIdx].couponPrice;
			// }
			// activityPrice += this.totalPrice * (1 - this.discount);
			// return activityPrice;
			// 先优惠再打折
			let activityPrice = 0;
			if (this.currentCouponIdx != -1) {
				activityPrice += this.couponList[this.currentCouponIdx].couponPrice + (this.totalPrice - this.couponList[this.currentCouponIdx].couponPrice) * (1 - this.discount);
			} else {
				activityPrice += this.totalPrice * (1 - this.discount);
			}

			return activityPrice;
		},
		payPrice() {
			// console.log(this.totalPrice, this.activityPrice);
			return this.totalPrice - this.activityPrice;
		},
		couponNum() {
			let couponNum = 0;
			for (let coupon of this.couponList) {
				couponNum += coupon.couponNum;
			}
			return couponNum;
		}
	},
	methods: {
		getSystemTime() {
			// 初始化时间
			getSysTime().then((res) => {
				const timestamp = res.data;
				// 更新dateUtil.js中的时间
				dateUtil.initDate(timestamp);
				this.initTime();
			});
		},
		initTime() {
			this.pickerArray = [0, 0, 0, 0];
			this.years = dateUtil.getYears();
			this.months = dateUtil.getMonths(this.years[this.pickerArray[0]]);
			this.days = dateUtil.getDays(this.months[this.pickerArray[1]]);
			this.times = dateUtil.getTimes(this.days[this.pickerArray[2]]);
			this.timeTemp =
				this.years[this.pickerArray[0]] + '年' + this.months[this.pickerArray[1]] + '月' + this.days[this.pickerArray[2]] + '日' + this.times[this.pickerArray[3]];
			this.pickTime = this.timeTemp;
			this.deliveryTime = this.timeTemp;
		},
		getDefaultAddress() {
			getDefaultAddress().then((res) => {
				this.address = res.data;
			});
		},
		getUserDiscount() {
			getUserDiscount().then((res) => {
				this.discount = res.data;
			});
		},
		getUserCouponList() {
			listUserCoupon(1).then((res) => {
				console.log(res.data);
				this.couponList = res.data;
				this.couponList = this.couponList.filter((item) => item.requirePrice <= this.totalPrice);
			});
		},
		changeType(type) {
			this.orderType = type;
			this.initTime();
		},
		showTimePopup() {
			this.$refs.timePopup.open('bottom');
		},
		bindChange(e) {
			this.pickerArray = e.detail.value;
			this.years = dateUtil.getYears();
			this.months = dateUtil.getMonths(this.years[this.pickerArray[0]]);
			this.days = dateUtil.getDays(this.months[this.pickerArray[1]]);
			this.times = dateUtil.getTimes(this.days[this.pickerArray[2]]);
			this.timeTemp =
				this.years[this.pickerArray[0]] + '年' + this.months[this.pickerArray[1]] + '月' + this.days[this.pickerArray[2]] + '日' + this.times[this.pickerArray[3]];
		},
		cancel() {
			this.$refs.timePopup.close();
		},
		sure() {
			if (this.orderType == 0) {
				this.pickTime = this.timeTemp;
			} else if (this.orderType == 1) {
				this.deliveryTime = this.timeTemp;
			}
			this.$refs.timePopup.close();
		},
		selectCoupon(index) {
			this.currentCouponIdx = index;
			// this.activityPrice = this.couponList[index].couponPrice;
			this.$refs.couponPopup.close();
		},
		/**
		 * 页面跳转
		 */
		gotoUserMessage() {
			uni.navigateTo({
				url: '/pages/user_message/user_message'
			});
		},
		gotoAddress() {
			uni.navigateTo({
				url: '/pages/user/service/user_address/user_address'
			});
		},
		async gotoCashDesk() {
			if (this.orderType == 2 && !this.address) {
				uni.showToast({
					title: '请完善收货信息',
					duration: 2000,
					icon: 'none',
					mask: true
				});
				return;
			}
			if (this.currentCouponIdx >= 0) {
				const timestamp = (await getSysTime()).data;
				const loseTimestamp = new Date(this.couponList[this.currentCouponIdx].endTime).getTime();

				if (timestamp > loseTimestamp) {
					uni.showToast({
						title: '当前选择的优惠券已过期，请重新选择',
						duration: 2000,
						icon: 'none',
						mask: true
					});
					this.getUserCouponList();
					return;
				}
			}
			let orderGoodsList = [];
			for (let i = 0; i < this.goodsList.length; i++) {
				let styleId = ''
				if(this.goodsList[i].styleInfo != null){
					styleId = this.goodsList[i].styleInfo.id;
				}
				orderGoodsList.push({
					goodsId: this.goodsList[i].id,
					goodsName: this.goodsList[i].name,
					goodsSpec: this.goodsList[i].spec,
					specInfo: this.goodsList[i].specInfo,
					goodsPrice: this.goodsList[i].price,
					goodsNum: this.goodsList[i].num,
					styleId: styleId
					// commission: this.goodsList[i].commission
				});
			}
			let userCouponId = null;
			if (this.currentCouponIdx >= 0) {
				userCouponId = this.couponList[this.currentCouponIdx].id;
			}
			let params = {
				shopId: uni.getStorageSync('shop').id,
				orderType: this.orderType,
				totalPrice: this.totalPrice,
				activityPrice: this.activityPrice,
				payPrice: this.payPrice,
				
				userMessage: this.userMessage,
				orderGoodsList: orderGoodsList,
				userCouponId: userCouponId
			};
			// for (let i = 0; i < this.goodsList.length; i++) {
			// 	params['orderGoodsList[' + i + '].goodsId'] = this.goodsList[i].id;
			// 	params['orderGoodsList[' + i + '].goodsName'] = this.goodsList[i].name;
			// 	params['orderGoodsList[' + i + '].goodsSpec'] = this.goodsList[i].spec;
			// 	params['orderGoodsList[' + i + '].goodsPrice'] = this.goodsList[i].price;
			// 	params['orderGoodsList[' + i + '].goodsNum'] = this.goodsList[i].num;
			// 	params['orderGoodsList[' + i + '].goodsStockId'] = this.goodsList[i].stockId;
			// }
			if (this.orderType == 1) {
				params.pickTime = this.pickTime;
			} else if (this.orderType == 2) {
				// params.deliveryPrice = this.deliveryPrice;
				params.addressId = this.address.id;
				params.deliveryTime = this.deliveryTime;
			}
			addOrder(params)
				.then((res) => {
					return new Promise((resolve, reject) => {
						if (res.code == 200) {
							resolve(res);
						} else {
							reject('创建订单失败');
						}
					});
				})
				.then((res) => {
					const orderId = res.data;
					console.log('orderId', res, res.data);
					uni.navigateTo({
						url: '/pages/order/cash_desk?payPrice=' + this.payPrice + '&orderId=' + orderId
					});
				});
		}
	}
};
</script>

<style scoped lang="less">
@theme-color: #ff5a14;

.container {
	background-color: #f5f5f5;
}

.border-bottom-grey {
	border-bottom: 1rpx solid #e8e9ee;
}

.header {
	background-color: #fff;
	padding: 30rpx;

	.order-type {
		display: flex;
		flex-direction: row;

		font-size: 32rpx;
		color: #fff;

		.type-item {
			flex: 1;
			text-align: center;
			padding: 20rpx 0;
			background-color: #e8e9ee;
			color: #9999aa;
		}

		.type-first {
			border-top-left-radius: 15rpx;
			border-bottom-left-radius: 15rpx;
		}

		.type-last {
			border-top-right-radius: 15rpx;
			border-bottom-right-radius: 15rpx;
		}

		// .pick-up {
		// 	border-top-left-radius: 15rpx;
		// 	border-bottom-left-radius: 15rpx;
		// }

		// .delivery {
		// 	display: block;
		// 	z-index: 10;
		// 	position: relative;
		// 	border-top-right-radius: 15rpx;
		// 	border-bottom-right-radius: 15rpx;
		// }

		// .delivery::before {
		// 	content: '';
		// 	display: block;
		// 	position: absolute;
		// 	top: 0;
		// 	right: 0;
		// 	bottom: 0;
		// 	left: 0;
		// 	z-index: -1;
		// 	transform: skew(20deg);
		// 	transform-origin: right bottom;
		// 	background-color: #e8e9ee;
		// 	border-radius: 15rpx;
		// }
		.active {
			background-color: @theme-color;
			color: #fff;
		}
	}

	.order-shop,
	.order-address {
		display: flex;
		flex-direction: row;
		margin-top: 40rpx;

		.pos-icon {
			padding: 25rpx;
			background-color: #e8e9ee;
			border-radius: 15rpx;
			color: @theme-color;
			font-size: 50rpx;
		}

		.shop-info,
		.address-info {
			display: flex;
			flex-direction: column;
			margin-left: 20rpx;
			gap: 20rpx;

			.shop-name,
			.address {
				font-size: 32rpx;
				font-weight: bold;
			}

			.shop-address,
			.info {
				font-size: 28rpx;
				display: flex;
				align-items: center;
			}
		}

		.address-info {
			flex: 1;
		}
	}
}

.order-content {
	padding: 30rpx;
}

.order-info,
.order-activity {
	background-color: #fff;
	padding: 0 20rpx;
	border-radius: 20rpx;

	.goods-item {
		display: flex;
		flex-direction: row;
		padding: 20rpx 0;
	}

	.goods-item .goods-image {
		width: 120rpx;
		height: 120rpx;
	}

	.goods-info {
		flex: 1;
		display: flex;
		flex-direction: column;
		margin-left: 30rpx;
		gap: 10rpx;
		font-size: 30rpx;

		.goods-spec {
			color: #a69999;
			font-size: 28rpx;
		}
	}

	.purchase {
		width: 150rpx;
		display: flex;
		flex-direction: column;
		justify-content: center;
		align-items: center;
	}

	.select-time-box,
	.user-message,
	.coupon,
	.discount {
		display: flex;
		flex-direction: row;
		padding: 30rpx 0;
		font-size: 30rpx;

		.pick-time,
		.delivery-time {
			color: @theme-color;
		}
	}
}

// 底层工具栏
.purchase-tool {
	width: 100%;
	height: 120rpx;
	background-color: #fff;
	display: flex;
	position: fixed;
	left: 0;
	bottom: 0;
	padding: 0 20rpx;
	z-index: 10;

	.tool-one,
	.tool-two {
		display: flex;
		align-items: center;
	}

	.tool-two {
		margin-left: 30rpx;
		flex: 2;

		.pay-price {
			font-size: 32rpx;
			color: @theme-color;
		}
	}

	.tool-three {
		flex: 1;
		display: flex;
		align-items: center;

		.purchase {
			background-color: @theme-color;
			padding: 18rpx 0;
			width: 100%;
			text-align: center;
			color: #fff;
			font-size: 30rpx;
			border-radius: 40rpx;
		}
	}
}

.picker-view {
	width: 750rpx;
	height: 500rpx;
	background-color: #fff;

	.item {
		display: flex;
		flex-direction: row;
		justify-content: center;
		align-items: center;
	}

	.indicator-item {
		color: @theme-color;
	}
}

.popup {
	position: relative;

	.tools {
		position: absolute;
		top: 0;
		left: 0;
		width: 100%;
		height: 100rpx;
		display: flex;
		flex-direction: row;
		justify-content: space-between;
		padding: 20rpx;
		border-bottom: 1rpx #ccc solid;
		background-color: @theme-color;
		color: #fff;

		.sure {
			color: #fff;
		}
	}
}

.coupon-list {
	padding: 0 20rpx;
}

.coupon-item {
	margin-top: 15rpx;
	display: flex;
	background-color: #fff;
	padding: 0 20rpx 0 10rpx;
	height: 200rpx;
	.item-left {
		flex: 1;
		position: relative;
		display: flex;
		flex-direction: column;
		justify-content: center;
		align-items: center;
		color: #fff;
	}
	.item-right {
		flex: 2;
		padding-left: 20rpx;
	}
}
.no-use-item-style {
	background-color: @theme-color;
	.item-serration {
		background-image: linear-gradient(-45deg, @theme-color 25%, transparent 25%, transparent), linear-gradient(-135deg, @theme-color, transparent 25%, transparent),
			linear-gradient(-45deg, transparent 75%, @theme-color 75%), linear-gradient(-135deg, transparent 75%, @theme-color 75%);
	}
}
.lose-item-style {
	background-color: #d5d5d5;
	.item-serration {
		background-image: linear-gradient(-45deg, #d5d5d5 25%, transparent 25%, transparent), linear-gradient(-135deg, #d5d5d5 25%, transparent 25%, transparent),
			linear-gradient(-45deg, transparent 75%, #d5d5d5 75%), linear-gradient(-135deg, transparent 75%, #d5d5d5 75%);
	}
}
.item-serration {
	content: '';
	position: absolute;
	left: -10rpx;
	top: 0;
	display: block;
	width: 10rpx;
	height: 100%;
	background-size: 20rpx 12rpx;
	background-color: #fff;
	background-position: 100% 35%;
}
</style>
